import React, { useEffect, useState, useRef } from 'react';
import { connect, history } from 'umi';
import { dateDisabled } from '@/common/regular';
import { Form, Button, Col, Row, Space, Card, notification, InputNumber, Radio } from 'antd';
import FormCondition from '@/components/FormCondition';
import SeatMapModal from './components/SeatMapModal'
import FixButton from '@/components/FlxButton'
import moment from 'moment';
const OfflineDetail = (props) => {
    const { history, loading, dispatch } = props;
    const { location } = history;
    const { query } = location;
    const { id, } = query;
    const [form] = Form.useForm();
    const [xqList, setXqList] = useState([])
    const [roomList, setRoomList] = useState([])
    const [seatConfigData, setSeatConfigData] = useState({})
    const [seatIdList, setSeatIdList] = useState([])
    const [subjectList, setSubjectList] = useState([])
    const [visible, setVisible] = useState(false)
    const [priceType, setPriceType] = useState('free')
    const { list = [] } = seatConfigData
    const changeSeatId = (id) => {

        const flag = seatIdList.find((item) => {
            return item == id
        })

        if (flag) {
            setSeatIdList(seatIdList.filter(val => {
                return val !== id
            }))
        } else {
            setSeatIdList([...seatIdList, id])
        }
    }
    const init = () => {
        if (id) {
            dispatch({
                type: 'answering/fetchTeacherScheduleDetail',
                payload: {
                    id
                },
                callback: (e) => {
                    const { teacherSchedule = {} } = e
                    let {
                        title,
                        teacherIds,
                        campusId,
                        classroomId,
                        fullAddress,
                        subjectIds,
                        startDate,
                        endDate,
                        minStudentAmount,
                        scheduleTimes,
                        remark,
                        priceType,
                        price,
                        integralPrice,
                        priceQaAmount,
                        seatIds = '',
                        maxToOrderDays,
                        minToOrderDays,
                        needChooseSeat
                    } = teacherSchedule
                    const payload = {
                        title,
                        teacherIds: teacherIds.split(',').map(item => { return Number(item) }),
                        subjectIds: subjectIds.split(',').map(item => { return Number(item) }),
                        campusId,
                        classroomId,
                        fullAddress,
                        minStudentAmount,
                        remark,
                        priceType,
                        price,
                        integralPrice,
                        priceQaAmount,
                        maxToOrderDays,
                        minToOrderDays,
                        needChooseSeat,
                        dateTime: [moment(startDate, 'YYYY-MM-DD'), moment(endDate, 'YYYY-MM-DD')]
                    }
                    setPriceType(priceType)
                    scheduleTimes = JSON.parse(scheduleTimes)
                    if (seatIds.length > 0) {
                        setSeatIdList(seatIds.split(','))
                    }
                    scheduleTimes.map(item => {
                        let timelist = [moment(item.startTime, 'HH:mm'), moment(item.endTime, 'HH:mm')]
                        payload.offineTime = timelist
                        payload['maxStudentAmount'] = item.maxStudentAmount
                    })
                    dispatch({
                        type: 'answering/fetchListCampusClassroom',
                        payload: {
                            campusId: campusId
                        },
                        callback: (e) => {
                            setRoomList(e)
                            const data = e.reduce((item, val) => {
                                const { id, seatConfig } = val
                                if (id === classroomId) {
                                    if (seatConfig.length > 0) {
                                        return JSON.parse(seatConfig)
                                    } else {
                                        return item
                                    }
                                }
                                return item
                            }, {})
                            setSeatConfigData(data)
                        }
                    })
                    form.setFieldsValue(payload)
                }
            })
        }
    }
    useEffect(() => {
        dispatch({
            type: 'answering/fetchListCampus',
            callback: (e) => {
                setXqList(e)
            }
        })
        dispatch({
            type: 'answering/fetchListSubject',
            callback: (e) => {
                setSubjectList(e)
            }
        })
        init()
    }, []);
    const fetchRoleEdit = () => {
        if (list.length > 0 && seatIdList.length === 0) {
            return notification.success({
                message: '温馨提示',
                description: '请先配置座位后提交',
            });
        }
        form.validateFields().then(async (values) => {
            console.log(values)
            const {
                title,
                teacherIds,
                campusId,
                classroomId,
                fullAddress,
                maxStudentAmount,
                dateTime,
                minStudentAmount,
                offineTime,
                remark,
                priceType,
                price,
                integralPrice,
                subjectIds,
                priceQaAmount,
                minToOrderDays,
                maxToOrderDays,
                needChooseSeat
            } = values
            const payload = {
                id,
                title,
                teacherIds: teacherIds.toString(),
                campusId,
                classroomId,
                fullAddress: fullAddress,
                maxStudentAmount,
                subjectIds: subjectIds.toString(),
                startDate: moment(dateTime[0]).format('YYYY-MM-DD'),
                endDate: moment(dateTime[1]).format('YYYY-MM-DD'),
                minStudentAmount,
                scheduleTimes: [{
                    scheduleType: 'self',
                    startTime: offineTime[0].format('HH:mm'),
                    endTime: offineTime[1].format('HH:mm'),
                    maxStudentAmount,
                }],
                remark,
                priceType,
                price,
                integralPrice,
                priceQaAmount,
                seatIds: needChooseSeat === '1' ? seatIdList.toString() : '',
                teachingMode: 'offline',
                minToOrderDays,
                maxToOrderDays,
                needChooseSeat
            }
            dispatch({
                type: 'answering/fakeSaveTeacherScheduleConfig',
                payload: {
                    teacherScheduleList: [payload]
                },
                callback: (e) => {
                    history.goBack()
                }
            })
        });
    };
    const formItems = [
        {
            label: '答疑主题',
            name: 'title',
            maxLength: 15
        },
        {
            label: '答疑老师',
            name: 'teacherIds',
            mode: 'multiple',
            type: 'teacher',
        },
        {
            label: '学科',
            name: 'subjectIds',
            rules: [{ required: false }],
            type: 'multiple',
            fieldNames: {
                label: 'subjectName',
                value: 'id'
            },
            select: subjectList
        },
        {
            label: '答疑校区',
            name: 'campusId',
            type: 'select',
            onChange: (e, { option }) => {
                console.log(e, option)
                const {
                    provinceName,
                    cityName,
                    districtName,
                    address
                } = option
                form.setFieldsValue({
                    classroomId: null,
                    fullAddress: provinceName + cityName + districtName + address,
                    campusId: e,
                })
                dispatch({
                    type: 'answering/fetchListCampusClassroom',
                    payload: {
                        campusId: e
                    },
                    callback: (e) => {
                        setRoomList(e)
                        setSeatConfigData({})
                        setSeatIdList([])
                    }
                })

            },
            fieldNames: {
                label: 'campusName', value: 'id',
            },
            select: xqList
        },
        {
            label: '答疑教室',
            name: 'classroomId',
            type: 'select',
            select: roomList,
            onChange: (e, { option }) => {
                const { seatConfig } = option
                if (seatConfig.length > 0) {
                    setSeatConfigData(JSON.parse(seatConfig))
                } else {
                    setSeatConfigData({})
                }
            },
            fieldNames: { label: 'classroomName', value: 'id', },
            extra: list.length > 0 ? <div direction='vertical'>
                <Space align='flex-start'>
                    <Form.Item
                        required
                        label={'是否需要选座'}
                        name={'needChooseSeat'}
                        rules={[
                            {
                                required: true,
                                message: '请设置天数',
                            },
                        ]}
                    >
                        <Radio.Group options={[{ label: '需要选座', value: '1' }, { label: '无需选座', value: '0' }]}></Radio.Group>
                    </Form.Item>
                    <Button onClick={() => {
                        setVisible({ show: true, detail: seatConfigData })
                    }} type='link'>预约座位排布</Button>
                </Space>
                <div>
                    <div style={{ color: '#999999' }}>
                        教室共计{list.filter(item => {
                            return item.status !== 'none'
                        }).length}座位，答疑可选座{seatIdList.length}个座位
                    </div>
                </div>

            </div> : ''
        },
        {
            label: '答疑地址',
            name: 'fullAddress',
            disabled: true
        },
        {
            label: '预约上限',
            name: 'maxStudentAmount',
            type: 'number',
            width: 240,
            addonAfter: '人'
        },
        {
            label: '开课周期',
            name: 'dateTime',
            dateDisabled: dateDisabled,
            type: 'rangePicker'
        },
        {
            type: 'formItem',
            extra: <div style={{ marginTop: 12, marginLeft: 64 }}>
                <Form.Item
                    required
                    name={'minToOrderDays'}
                    rules={[
                        {
                            required: true,
                            message: '请设置天数',
                        },
                    ]}
                >

                    <InputNumber style={{ margin: '0 12px', width: 595 }} addonAfter={'天前不允许预约'} addonBefore="离开课"></InputNumber>
                </Form.Item>
                <Form.Item
                    required
                    name={'maxToOrderDays'}
                    rules={[
                        {
                            required: true,
                            message: '请设置天数',
                        },
                    ]}
                >

                    <InputNumber style={{ margin: '0 12px', width: 595 }} addonAfter={'天内不允许预约'} addonBefore="离开课"></InputNumber>
                </Form.Item>
            </div>,
            formItem: <Form.Item
                required
                label={'开班限制'}
                name={'minStudentAmount'}
                rules={[
                    {
                        required: true,
                        message: '请设置最小人数',
                    },
                ]}
            >
                <InputNumber addonAfter={
                    <span style={{ marginLeft: 10 }}>人，将自动取消答疑</span>
                } addonBefore="开课周期时间结束后，预约人数低于" />
            </Form.Item>
        },
        {
            label: '答疑时间',
            name: 'offineTime',
            type: 'timePicker',
            timeType: 'rangePicker'
        },
        {
            label: '备注说明',
            name: 'remark',
        },
        {
            label: '答疑价格',
            name: 'priceType',
            onChange: (e) => {
                setPriceType(e.target.value)
            },
            type: 'radio',
            select: {
                free: '免费',
                price: '付费'
            },
            extra: priceType !== 'free' && <Row style={{ marginTop: 8 }} gutter={[8, 8]}>
                <Col span={18}>
                    <Form.Item
                        required
                        name={'price'}
                        rules={[
                            {
                                required: true,
                                message: '请设置支付金额',
                            },
                        ]}
                    >

                        <InputNumber addonAfter={
                            '元'
                        } addonBefore="支付" style={{ margin: '0 12px', width: 240 }}></InputNumber>
                    </Form.Item>
                </Col>

                <Col span={18}>
                    <Form.Item
                        required={false}
                        name={'integralPrice'}
                        rules={[
                            {
                                required: false,

                            },
                        ]}
                    >
                        <InputNumber addonAfter={
                            '答疑积分'
                        } addonBefore="支付" style={{ margin: '0 12px', width: 240 }}></InputNumber>
                    </Form.Item>
                </Col>
                <Col span={18}>
                    <Form.Item
                        required={false}
                        name={'priceQaAmount'}
                        rules={[
                            {
                                required: false,
                            },
                        ]}
                    >

                        <InputNumber style={{ margin: '0 12px', width: 240 }} addonAfter={'次数'} addonBefore="消耗"></InputNumber>
                    </Form.Item>
                </Col>
            </Row>
        },


    ];
    return (
        <Card extra={<Button onClick={() => { history.goBack() }} type='link'>返回列表</Button>} title={id ? '编辑线下答疑' : '新建线下答疑'} style={{ position: 'relative' }}>
            <Row gutter={[24, 24]}>
                <Col span={12}>
                    <FormCondition
                        formItemLayouts={{
                            labelCol: {

                            },
                            wrapperCol: {

                            },
                        }}
                        form={form}
                        formItems={formItems}
                    ></FormCondition>
                </Col>

            </Row>
            <SeatMapModal
                onOk={(e) => { setSeatIdList(e) }}
                seatIdList={seatIdList}
                visible={visible}
                onClose={() => setVisible(false)}
            ></SeatMapModal>
            <FixButton onOk={() => { fetchRoleEdit() }}></FixButton>
        </Card>
    );
}
export default connect(({ loading }) => ({
    loading: loading.effects['liveStreaming/fakeSaveFaceToFace'],
}))(OfflineDetail);